<template>
  <v-layout type="main">
    <div v-if="version != null">
      <div class="layout-top">
        <div class="rollback" @click="$router.push('/gameTask')">
          <img src="~@/assets/img/prev.png" alt="" />
          <span>返回</span>
        </div>

        <div class="code-description">
          <div class="dea_top">
            <div>
              <el-image
                class="nav_box"
                :src="
                  detailData.avatar
                    ? detailData.avatar
                    : require('@/assets/img/drone3.jpg')
                "
                fit="fit"
              ></el-image>
            </div>

            <div class="header_box">
              <div class="code-desc-header">
                <div class="title">
                  <div class="title-header">
                    <span>{{ detailData.name }}</span>
                  </div>

                  <div class="code-tags">
                    <div class="user-tag tag">
                      <img src="~@/assets/img/user.png" alt="" />
                      {{
                        detailData.create_user &&
                        (detailData.create_user.nick_name ||
                          detailData.create_user.username)
                      }}
                    </div>

                    <div
                      :class="[
                        'status-tag tag',
                        {
                          danger: version.status === 'terminated',
                          warning:
                            version.status != 'terminated' &&
                            version.status != 'running',
                          success: version.status === 'running',
                        },
                      ]"
                    >
                      {{ statusMap[version.status] }}
                    </div>

                    <div class="version-tag tag">
                      <div class="ver-title">
                        <img src="~@/assets/img/branch.png" alt="" />
                        <span>版本 {{ version.version }}</span>
                        <i class="el-icon-arrow-down el-icon--right"></i>
                      </div>
                      <div class="content">
                        <div
                          class="ver-item"
                          v-for="item in versionOptions"
                          :key="item.id"
                          @click="dropdownChange(item)"
                        >
                          {{ item.version }}
                        </div>
                      </div>
                    </div>

                    <div class="time-tag tag">
                      <span>创建时间：</span>
                      {{ detailData.create_time }}
                    </div>
                  </div>

                  <div class="staet_box">
                    <plug-state :statusStr="version.status" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="btns-container">
          <div class="alick-handle-btns">
            <el-button
              class="handle-btn"
              type="success"
              size="medium"
              @click="start"
              v-show="version.status == 'terminated'"
            >
              启动
            </el-button>
            <el-button
              class="handle-btn"
              type="danger"
              size="medium"
              @click="stop"
              v-show="version.status != 'terminated'"
            >
              停止
            </el-button>

            <el-popover placement="bottom-end" width="80" trigger="hover">
              <div class="alick-popover-handle-btns">
                <el-button
                  class="handle-btn"
                  type="warning"
                  size="medium"
                  @click="exportModel"
                  >导出模型</el-button
                >
                <el-button
                  class="handle-btn"
                  type="warning"
                  size="medium"
                  @click="addVersion"
                  >新增版本</el-button
                >
              </div>
              <el-button
                class="handle-btn"
                type="warning"
                size="medium"
                slot="reference"
                >更多</el-button
              >
            </el-popover>
          </div>
        </div>
      </div>

      <el-tabs
        v-model="nowRouter"
        @tab-click="skip"
        v-show="!$route.meta.hideDetails"
      >
        <el-tab-pane
          :label="e.meta.title"
          :name="`${e.name}`"
          v-for="(e, i) in thisRouter"
          :key="i"
        />
      </el-tabs>

      <div
        :class="[
          'layout-content',
          { 'layout-content-nodetail': $route.meta.hideDetails },
        ]"
      >
        <router-view
          class="content-detail"
          :detailData="detailData"
          :version.sync="version"
          @getDetail="getDetail"
          v-if="version != null"
        />
      </div>
      <div v-if="showExportModelDialog">
        <plug-export-model
          :show_file="showExportModelDialog"
          @infoShow="infoShowExport"
          :model_id="model_id"
          :biz_id="version.id"
          :business_type="2"
        />
      </div>
    </div>
  </v-layout>
</template>

<script>
import plugState from "@/components/module/plug-state";
import { getModelBySource } from "@/api/model";
import { mapActions, mapState } from "vuex";
import {
  getGameTaskDetail,
  putGameTask,
  getAllGameTaskVersions,
  startGameTaskVersion,
  stopGameTaskVersion,
  getGameTaskVersionDetail,
} from "@/api/gameTask";
import { domain } from "@/config";
export default {
  data() {
    return {
      nowRouter: this.$route.name,
      thisRouter: [],
      detailData: null,
      taskForm: {},
      model_id: null,
      version: null,
      versionOptions: [],
      modelForm: { visibility: 0 },
      baseSubmitRules: {
        name: [
          { required: true, message: "该项为必填项" },
          { required: true, min: 1, max: 40, message: "长度在1到40个字符" },
        ],
        desc: [
          { required: true, message: "该项为必填项" },
          { required: true, min: 1, max: 200, message: "长度在1到40个字符" },
        ],
      },
      modelSubmitRules: {
        model_id: [{ required: true, message: "该项为必填项" }],
      },
      showUpdateBaseDialog: false,
      showExportModelDialog: false,
      modelOptions: [],
      model: null,
      verArray: null,
      source_version_id: this.$route.query.source_version_id,
      podUrl: null,
      forceRerenderKey: 0,
      allChecked: false,
    };
  },
  components: { plugState },
  methods: {
    ...mapActions(["getTaskList", "updateDetail"]),
    forceRerender() {
      this.forceRerenderKey += 1;
    },
    unfoldChange(val) {
      this.$store.commit("GAMETASKUNFOLDCHANGE", val);
    },
    skip() {
      let path = `/gameTask/${
        this.thisRouter.filter((e) => e.name == this.nowRouter)[0].path
      }`;
      if (path == this.$route.path) return;
      this.$router.push({
        path,
        query: {
          id: this.$route.query.id,
          source_version_id: this.$route.query.source_version_id,
        },
      });
    },
    dropdownChange(val) {
      this.version = val;
      console.log('val',val);
      this.versionChange();
    },
    tableItemHandler(val) {
      this.updateDetail(val);
      this.unfoldChange(false);

      this.$router.push({
        path: "/gameTask",
        query: {
          id: val.id,
        },
      });
      this.forceRerender();
    },
    async getTaskVersions() {
      let ret = await getAllGameTaskVersions({
        gameTaskId: this.$route.query.id,
        type: 1,
      });
      this.versionOptions = ret.data;
      console.log("this.versionOptions", this.versionOptions);
      let ve;
      if (this.versionOptions.length > 0) {
        // ve = this.versionOptions[0];
        if (this.$route.query.version) {
          ve = this.versionOptions.filter(
            (item) => item.version === this.$route.query.version
          )[0];
          console.log('12345678',ve);
        } else {
          ve = this.versionOptions[0];
          console.log('1234',ve);
        }
      }
      if (this.source_version_id) {
        for (let i = 0; i < this.versionOptions.length; i++) {
          if (this.source_version_id == this.versionOptions[i].id) {
            ve = this.versionOptions[i];
          }
        }
      }
      let res = await getGameTaskVersionDetail({ id: ve.id });
      this.version = res.data;
      console.log("version11111", this.version);
      if (this.version && this.version.id) {
        await this.getVersionDetail();
        this.genUrl();
      }
      this.$forceUpdate();
    },
    async getVersionDetail() {
      let res = await getGameTaskVersionDetail({ id: this.version.id });
      this.version = res.data;
      console.log("this.version", this.version);
    },
    versionChange() {
      this.getVersionDetail();
    },
    async handleChange(val) {
      console.log(val);
      this.detailData = val;
      this.updateDetail(val);
      this.$router.push({
        path: "/gameTask",
        query: {
          id: val.id,
        },
      });
    },
    async getDetail() {
      if (this.$route.query.id) {
        let res = await getGameTaskDetail({ id: this.$route.query.id });
        this.detailData = res.data;
        this.updateDetail(res.data);
        this.taskForm = JSON.parse(JSON.stringify(this.detailData));
      }
    },
    updateBase() {
      this.showUpdateBaseDialog = true;
    },

    commitBase() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let res = await putGameTask(this.taskForm);
          if (res && res.data) {
            this.getDetail();
            this.showUpdateBaseDialog = false;
          }
        }
      });
    },
    cancelBase() {
      this.showUpdateBaseDialog = false;
    },
    addVersion() {
      let query = {
        task_id: this.detailData.id,
      };
      this.$router.push({
        path: "/gameTask/detail",
        query,
      });
    },
    async exportModel() {
      if (!this.$route.query.id) return;
      let data = {
        source: this.version.id,
      };
      let res = await getModelBySource(data);
      if (res && res.data) {
        this.model_id = res.data.id;
      }
      this.showExportModelDialog = true;
    },

    start() {
      if (this.version) {
        startGameTaskVersion({ id: this.version.id });
      }
    },
    async stop() {
      if (this.version) {
        await stopGameTaskVersion({ id: this.version.id });
        this.getDetail();
        this.$forceUpdate();
      }
    },
    infoShowExport(data) {
      this.showExportModelDialog = data;
    },
    goToLink() {
      this.genUrl();
      let path = this.podUrl;
      console.log("path", path);
      if (path) {
        window.open(path, "_blank");
      }
    },
    infoData(data) {
      console.log("infoData", data);
      this.getDetail();
      this.$forceUpdate();
    },
    genUrl() {
      if (this.version.status != "running" || !this.version.tcp_port_list) {
        return null;
      }
      let tcp_port_list = this.version.tcp_port_list;
      let simulationFrontUrl = process.env.VUE_APP_SIMULATION_URL;
      console.log(simulationFrontUrl);
      console.log(domain);
      let port4000List = tcp_port_list.filter(
        (map) => map.containerPort == "4000"
      );
      let port4001List = tcp_port_list.filter(
        (map) => map.containerPort == "4001"
      );
      if (port4000List.length && port4001List.length) {
        let nodePort4000 = port4000List[0].nodePort;
        let nodePort4001 = port4001List[0].nodePort;
        let endpoint = tcp_port_list[0].endpoint.split(":")[0];
        let url = `${simulationFrontUrl}/#/Menu?IP=${endpoint}&port1=${nodePort4000}&port2=4001&port3=${nodePort4001}`;
        this.podUrl = url;
      }
    },
  },
  computed: mapState({
    taskList: (state) => state.gameTaskStore.taskList,
    isCollapse: (state) => state.gameTaskStore.isCollapse,
    // detailData: (state) => state.gameTaskStore.detail,
  }),
  mounted() {
    let temp = this.$router.options.routes.filter(
      (e) => e.name == "gameTask" && e.children
    );
    this.thisRouter = temp[0].children.filter((e) => !e.meta.hideDetails);

    this.getTaskList();

    this.getDetail();
    this.getTaskVersions();
    this.$EventBus.$on("gameTask", (e) => {
      console.log(e);
      this.getVersionDetail();
    });
  },
  destroyed() {
    this.$EventBus.$off("task");
  },
};
</script>
<style lang="less" scoped>
@import "~@/assets/css/detail-layout.less";

.task-box {
  display: flex;

  .task-container {
    width: 100%;
    // margin-left: 220px;
    margin-left: 470px;
  }
}

.el-dropdown-link {
  border: 1px solid rgba(#808080, 0.5);
  padding: 5px 10px;
  border-radius: 10px;
  position: relative;
  padding-left: 28px;
  background: #eee;
  top: 3px;

  span::before {
    content: "";
    width: 16px;
    height: 16px;
    background: url(~@/assets/img/branch.png) no-repeat center;
    background-size: cover;
    margin-top: 3px;
    position: absolute;
    left: 6px;
    top: 4px;
  }
}
</style>
